package org.yh.moodpraise.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.yh.moodpraise.dao.MoodMapper;
import org.yh.moodpraise.model.MoodVo;
import org.yh.moodpraise.rabbitmq.MQSender;

import java.util.List;

/**
 * @Author: yh
 * @Date: 2020/6/20
 * @Description:
 */

@Service
public class MoodService {
    @Autowired
    MoodMapper moodMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    MQSender mqSender;

    public  List<MoodVo> getAllMoodVos() {
        return moodMapper.getAllMoodVos();
    }

    public int updatePraiseNum(Integer moodId) {
        return moodMapper.updatePraiseNum(moodId);
    }

    //更新数据库的点赞数
    public int updatePraiseIncrement(Integer moodId,Integer praiseIncrement){
        return moodMapper.updatePraiseIncrement(moodId,praiseIncrement);
    }

    //利用消息队列异步更新数据库
    public int praiseIncrementForMq(Integer moodId,Integer praiseIncrement){
        mqSender.sendMessage(moodId+":"+praiseIncrement);
        return 2;
    }


    public List<MoodVo> findMoodVosForRedis() {
        //查询所有的moodVo
        List<MoodVo>moodVos =moodMapper.getAllMoodVos();
       if(moodVos ==null || moodVos.size()==0){
           return null;
       }
        //更新点赞数量
        //新的点赞数量=数据库的点赞数量+redis中新增的点赞数量
        for (MoodVo moodVo : moodVos) {
            System.out.println(moodVo);
            moodVo.setPraise_num(moodVo.getPraise_num()+ redisTemplate.opsForSet().size(moodVo.getId()).intValue());
        }
        return moodVos;
    }
}
